package djrain.lilochat.client;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;

import djrain.lib.ToastEx;
import djrain.lilochat.client.LocationHelper.OnLocationChangeListener;

public class Lilo extends MapActivity
{
	private static final String tag = "lilo";

	String id = android.os.Build.MODEL;

//	private EditText input = null;
	private MapController controller = null;
	private LocationHelper locationHelper;
	private SocketClient client = new SocketClient();

	private boolean isConnect = false;
	private LiloMapView liloMapView;
//	private Context mContext;

	private Lolople iam;
	private Lolople you;

//	private Location iamLoaction;

	private EditText input;

	private CheckBox iamCenter;
	private boolean isIamCenter = true;
	

	
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lilo);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		
		Bitmap iambitmap = BitmapFactory.decodeResource( getResources(), R.drawable.lilo_config_icon_iam);
		iam = new Lolople(iambitmap);
		Bitmap youbitmap = BitmapFactory.decodeResource( getResources(), R.drawable.lilo_config_icon_you);
		you = new Lolople(youbitmap);


		liloMapView = (LiloMapView) findViewById(R.id.mapview);

		controller = liloMapView.getController();
		controller.setZoom(13);

		getUserInfo();
		isConnect = client.connectServer(new LiloMessage(this));

		locationHelper = new LocationHelper(this);
		Location lo = locationHelper.getLocation();
		if (lo != null)
		{
			iam.overlay.setGeoPoint(LocationHelper.location2geopoint(lo));
			controller.setCenter(iam.overlay.getGeoPoint());

			if (isConnect)
				client.sendIam(iam.displayname,lo);
		}


		final List<Overlay> points = liloMapView.getOverlays();
		points.add(iam.overlay);
		if (lo != null)

		liloMapView.invalidate();

		locationHelper.setOnLocationChangeListener(onLocationChangeListener);

		input = (EditText) findViewById(R.id.input);
		
		iamCenter = (CheckBox) findViewById(R.id.iamCenter);
		iamCenter.setChecked(isIamCenter);

		
		mPm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Wake_FULL_WAKE_LOCK");
	}

	private void getUserInfo()
	{
		try
		{
			TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			if (tm != null)
			{
				iam.line1Number = tm.getLine1Number();
				iam.simSerialNumber = tm.getSimSerialNumber();
				iam.displayname = iam.line1Number + "," + iam.simSerialNumber;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	private OnLocationChangeListener onLocationChangeListener = new OnLocationChangeListener()
	{
		public void onLocationChanged(Location location)
		{
			GeoPoint geoPoint = LocationHelper.location2geopoint(location);
			// mapView.getOverlays().clear();

			// final List<Overlay> points = liloMapView.getOverlays();
			// points.clear();

			// 경로표시
			// if (points.size() == 0)
			// points.add(new OverlayRoot(geoPoint, null, 1, 999));
			// else
			// points.add(new OverlayRoot(geoPoint, lastgeoPoint, 2, 999));
			// lastgeoPoint = geoPoint;

			iam.overlay.setGeoPoint(geoPoint);

			// overlay item 추가
			// mapView.getOverlays().clear();
			// overlay = null;
			// overlay= new UnitItemizedOverlay(Lilo.this,
			// Lilo.this.getResources().getDrawable(R.drawable.arraw));
			// OverlayItem overlayItem = new OverlayItem(geoPoint,"11","22");
			// overlay.addOverlay(overlayItem);
			// mapView.getOverlays().add(overlay);
			// mapView.invalidate();

			// 중심이동
			if(isIamCenter)
				controller.animateTo(geoPoint);
			// 서버통지
			if (isConnect)
				client.sendLilo(location);

			// 속도에 따른 표시 축척 변경
			// if( location.hasSpeed() )
			// {
			// int speed = (int) location.getSpeed();
			// if(speed <= 1)
			// speed = MIN_SPEED;
			// controller.zoomToSpan(speed*ZOOM_CONST,speed*ZOOM_CONST );
			// }
			//
			// try {
			// ZOOM_CONST = Integer.parseInt(input.getText().toString());
			// if (ZOOM_CONST > 0) {
			// Log.e(tag, "MapActivity isRouteDisplayed:" + ZOOM_CONST);
			// controller.zoomToSpan(ZOOM_CONST, ZOOM_CONST);
			// }
			// } catch (NumberFormatException e) {
			// e.printStackTrace();
			// }

			liloMapView.invalidate();

//			ToastEx.makeText(mContext, "" + geoPoint);
		}
	};

	@Override
	protected void onResume()
	{
		super.onResume(); // Start updates (doc recommends delay >= 60000 ms)
		locationHelper.onResume();
		mWakeLock.acquire();

	}

	@Override
	protected void onPause()
	{
		super.onPause(); // Stop updates to save power while apppaused
		locationHelper.onPause();
		if (mWakeLock.isHeld())
		{
			mWakeLock.release();
		}
	}

	@Override
	protected boolean isRouteDisplayed()
	{
//		Log.i("djrain", "isRouteDisplayed:");
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		Log.i("djrain", "Lilo onCreateOptionsMenu:");
		menu.add(R.string.lilo_config).setIcon(R.drawable.lilo_config_icon).setIntent(new Intent(this, LiloConfig.class));

		return super.onCreateOptionsMenu(menu);
	}


	PowerManager mPm;
	WakeLock mWakeLock;

	
	public void updateYou(String message)
	{
	
	}

	public void updateYouChat(String message)
	{
		you.message = message;
		liloMapView.invalidate();
		
	}

	public void updateYouLocation(GeoPoint geoPoint)
	{		
		you.overlay.setGeoPoint(geoPoint);
	}
	

	public void onIamCenter(View v){
		isIamCenter = !isIamCenter;
		iamCenter.setChecked(isIamCenter);
		if(isIamCenter)
			controller.animateTo(iam.overlay.getGeoPoint());
	}
	
/*******************************************************************************************
 ******************************************************************************************* 
 *******************************************************************************************/
	
	
	
	StringBuffer sb = new StringBuffer(512);
	public void setReceiveMessage(String message)
	{
		Log.e("djrain","Lilo setReceiveMessage:"+message);
		
		if(sb.length() > 500)
			sb.delete(500, sb.length());
		sb.insert(0, message);
		
		TextView debug = (TextView) findViewById(R.id.debug);
		debug.setText(sb.toString());
	}

	public void onTest(View v)
	{
		ToastEx.makeText(this, "Test");
		LocationHelper.MINTIME = 1000;
		LocationHelper.MINDISTANCE = 0f;
		LocationHelper._DEBUG = true;
		locationHelper.onPause();
		locationHelper.findBestProvider();
		locationHelper.onResume();
	}

	public void onReal(View v)
	{
		ToastEx.makeText(this, "Real");
		LocationHelper._DEBUG = false;
		LocationHelper.MINTIME = 3000;
		LocationHelper.MINDISTANCE = 0f;

		locationHelper.onPause();
		locationHelper.findBestProvider();
		locationHelper.onResume();
	}
	
	public void onDebug(View v){
		View tv = findViewById(R.id.debug);
		tv.setVisibility(View.GONE - tv.getVisibility());
		
		((CheckBox)v).setChecked(tv.getVisibility() == View.VISIBLE);

		ToastEx.makeText(this, "Debug box" + tv.getVisibility());
	}
	
}
